#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module to get PageRank value as showed by the Google Toolbar
Return a string with the TBPR of the given URL. If the URL is
not ranked return -1 

Found here: http://pagerank.gamesaga.net/
And slightly modified
"""

import httplib

def HashURL (url):
    SEED = "Mining PageRank is AGAINST GOOGLE'S TERMS OF SERVICE. Yes, I'm talking to you, scammer."
    Result = 0x01020345
    for i in range(len(url)) :
        Result ^= ord(SEED[i%len(SEED)]) ^ ord(url[i])
        Result = Result >> 23 | Result << 9
        Result &= 0xffffffff 
    return '8%x' % Result

def get(url):
    url = url.strip("\a\b\f\n\r\t\v")
    conn = httplib.HTTPConnection('www.google.com')
    googleurl = '/search?client=navclient-auto&features=Rank:&q=info:' \
        + url + '&ch=' + HashURL(url)
    conn.request("GET", googleurl)
    response = conn.getresponse()
    data = response.read()
    status = response.status
    conn.close()
    pr = data.split(":")[-1].strip('\n')
    if len(pr) == 0 or status != 200:
        pr = '-1'
    return pr

if (__name__ == "__main__"):
    urls = ('www.google.com',
            'www.mit.edu',
            'www.ricette-facili.it',
            'uninews.unicredito.it/open/?a=9284',
            'http://www.dagoneye.it/blog/index.php?tags=899',
            'http://www.ricette-facili.it/primi-piatti/7/zuppa-di-cipolle/',
            'http://microformats.org/wiki?title=what-are-microformats&diff=0&oldid=18544')
    for url in urls:
        pr = get(url)
        print url, pr
